package com.docking.heylo.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.docking.heylo.ThreadContext;
import com.docking.heylo.dao.entity.*;
import com.docking.heylo.dao.mapper.*;
import com.docking.heylo.enums.EDeleteStatus;
import com.docking.heylo.enums.EMessageType;
import com.docking.heylo.enums.EPostState;
import com.docking.heylo.enums.EUserBlack;
import com.docking.heylo.exception.GeneralException;
import com.docking.heylo.service.*;
import com.docking.heylo.utils.HeyloMessageSource;
import com.docking.heylo.web.dto.PostCommentsDto;
import com.docking.heylo.web.dto.PostDto;
import com.docking.heylo.web.dto.PushPostDto;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PostServiceImpl implements IPostService {

    @Resource
    private PostMapper postMapper;

    @Resource
    private PostTagMapper postTagMapper;

    @Resource
    private PostCommentsMapper commentsMapper;

    @Resource
    private PostLikeMapper postLikeMapper;

    @Autowired
    private IPostTagService postTagService;

    @Autowired
    private ICacheService cacheService;

    @Autowired
    private IMessageService messageService;

    @Resource
    private UserMapper userMapper;

    @Autowired
    private IUserService userService;

    @Resource
    private UserSlidingUpMapper userSlidingUpMapper;

    @Autowired
    private HeyloMessageSource messageSource;

    @Autowired
    private PersonalInformationMapper personalInformationMapper;

    @Resource
    private UserBlacklistMapper userBlacklistMapper;

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void savePost(Post post) {
        savePost(post, EPostState.publish);

    }

    private void savePost(Post post, EPostState postState){
        String cover = post.getPicture().split(",")[0];

        post.setCoverPic(cover);
        post.setCrtAt(new Date());
        post.setUserId(ThreadContext.userId());
        post.setState(postState.getState());
        post.setLike(0);
        post.setComments(0);
        postMapper.insertSelective(post);

        // 作品数 +1
        userService.pushPost(ThreadContext.userId());

        cacheService.pushPost(post, ThreadContext.bigA() ? 3 : ThreadContext.type());

    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void pushPost(PushPostDto dto) {
        Post post = new Post();
        BeanUtils.copyProperties(dto, post);
        post.setLat(BigDecimal.valueOf(dto.getLat()));
        post.setLon(BigDecimal.valueOf(dto.getLon()));

        // 保存作品
        savePost(post, EPostState.publish);

        // aite
        if(dto.getAite() != null && dto.getAite().length > 0){
            postTagService.savePostTag(dto.getAite(), ThreadContext.userId(), post.getId());

            messageService.sendMessage(dto.getAite(), "您的好友发新动态了，快来看看吧！", new HashMap<String, String>(){{
                put("type", EMessageType.new_post.getValue() + "");

                put("body", JSONObject.toJSONString(new HashMap<String, Object>(){{
                    put("id", post.getId().toString());
                    put("userId", ThreadContext.userId() + "");
                    put("nickName", ThreadContext.authorize.get().getUser().getRealName());
                    put("avatar", ThreadContext.authorize.get().getUser().getAvatar());
                }}));
            }});
        }
    }

    @Override
    public PageInfo<Map<String, Object>> postByUserId(PostDto postDto) {
        PageHelper.startPage(postDto.getPageNumber(), postDto.getSize());

        return new PageInfo<>(postMapper.selectPostByUserId(postDto.getUserId(),
                EPostState.publish.getState()));
    }

    @Override
    public PageInfo<Map<String,Object>> postComments(PostCommentsDto commentsDto) {
        PageHelper.startPage(commentsDto.getPageNumber(),commentsDto.getSize());
        PageHelper.orderBy("crt_time desc");
        return new PageInfo<>(postTagMapper.selectComments(ThreadContext.userId(), commentsDto.getPostId()));
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void pushPostComment(PostComments postComments) {
        postComments.setCrtTime(new Date());
        postComments.setInformationId(ThreadContext.informationId());
        commentsMapper.insertSelective(postComments);
        postMapper.submitComment(postComments.getPostId());

        // 修改评论数
        Post post = postMapper.selectByPrimaryKey(postComments.getPostId());

        cacheService.postComment(post.getUserId());
    }

    @Override
    public Post selectByPrimaryKey(int id) {
        return postMapper.selectByPrimaryKey(id);
    }

    @Override
    public Post selectLastPostForUser(Integer userId) {

        return postMapper.selectLastPostForUser(userId);
    }

    @Override
    public List<Map<String, Object>> my_buddy_post() {
        return postMapper.selectMyBuddyPost(ThreadContext.userId());
    }

    @Override
    public Map<String, Object> panel(Integer id) {
        return postMapper.panel(id);
    }


    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void like(PostDto post) {
        PostLike like = selectByUserIdAndPostId(ThreadContext.userId(), post.getId());
        Post dbPost = selectByPrimaryKey(post.getId());

        if(like == null || like.getDeletd() == EDeleteStatus.delete.getValue()){
            if(like == null){
                postLikeMapper.insertSelective(new PostLike(){{
                    setUserId(ThreadContext.userId());
                    setPostId(post.getId());
                    setCrtAt(new Date());
                    setDeletd(EDeleteStatus.notDeleted.getValue());
                }});
            }else{
                postLikeMapper.updateByPrimaryKeySelective(new PostLike(){{
                    setId(like.getId());
                    setDeletd(EDeleteStatus.notDeleted.getValue());
                }});
            }

            // 缓存Post喜欢数 +1
            cacheService.postLike(dbPost.getUserId(), true);

            // Post喜欢数 +1
            postMapper.like(dbPost.getId());

            // Post用户喜欢数 +1
            personalInformationMapper.like(dbPost.getUserId());
        }else{
            // 缓存Post 喜欢数 -1
            cacheService.postLike(dbPost.getUserId(), false);

            // 删除当前用户喜欢记录
            postLikeMapper.updateByPrimaryKeySelective(new PostLike(){{
                setId(like.getId());
                setDeletd(EDeleteStatus.delete.getValue());
            }});

            // Post 喜欢数 -1
            postMapper.cancelLike(dbPost.getId());

            // Post用户喜欢数 -1
            personalInformationMapper.cancelLike(dbPost.getUserId());
        }
    }


    public PostLike selectByUserIdAndPostId(int userId, int postId){
        PostLikeExample example = new PostLikeExample();
        PostLikeExample.Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo(userId);
        criteria.andPostIdEqualTo(postId);

        List<PostLike> likes = postLikeMapper.selectByExample(example);

        return likes.size() > 0 ? likes.get(0) : null;
    }


    @Override
    public boolean load() {
        List<Post> posts = postMapper.selectByExample(new PostExample());
        for(Post post : posts){
            User user = userMapper.selectByPrimaryKey(post.getUserId());
            cacheService.pushPost(post, user.getType().intValue());
        }
        return true;
    }

    @Override
    public void slidingUp(PostDto post) {
        UserSlidingUp sup = userSlidingUpMapper.selectByPrimaryKey(ThreadContext.userId());
        if(sup == null){
            sup = new UserSlidingUp(){{
                setCumulative(0);
                setLastTime(new Date());
                setUserId(ThreadContext.userId());
            }};
            userSlidingUpMapper.insertSelective(sup);
        }else{
            if(!DateUtil.format(sup.getLastTime(), "yyyy-MM-dd").equals(DateUtil.format(new Date(),"yyyy-MM-dd"))){
                sup.setCumulative(0);
            }
        }

        sup.setCumulative(sup.getCumulative() + 1);
        sup.setLastTime(new Date());
        if(sup.getCumulative().intValue() > 5 ){
            throw new GeneralException("当日上滑已达上限");
        }

        userSlidingUpMapper.updateByPrimaryKeySelective(sup);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void remove(Post post) {
        Post dbPost = selectByPrimaryKey(post.getId());
        if(dbPost == null || dbPost.getUserId().intValue() != ThreadContext.userId()){
            throw new GeneralException(messageSource.getMessage("post.notfind"));
        }

        // 移除缓存中的作品
        cacheService.post_remove(new HashMap<String, Object>(){{
            put("userId", ThreadContext.userId());
        }});

        // 删除作品
        postMapper.deleteByPrimaryKey(dbPost.getId());

        // 当前用户作品数 -1
        personalInformationMapper.removePost(dbPost.getUserId());

    }

    @Override
    public void report(PostDto post) {
        userBlacklistMapper.insertSelective(new UserBlacklist(){{
            setTagId(post.getId());
            setUserId(ThreadContext.userId());
            setType(EUserBlack.zuo_ping.getValue());
        }});
    }

    @Override
    public void commentsReport(PostDto post) {
        userBlacklistMapper.insertSelective(new UserBlacklist(){{
            setTagId(post.getId());
            setUserId(ThreadContext.userId());
            setType(EUserBlack.zuo_ping_ping_lun.getValue());
        }});
    }


}
